<?php
//include('addons/services/XdataService.class.php');



class PublicAction extends Action
{
    public function _initialize() {
		
	}
    /**
     * 
     *登陆 
     * @author sudi
     * @date 2012.1.4
     * 
     */
     public function login()
    {
        $this->redirect('land');   
    }
     public function land()
    {
        $this->display('Tpl/default/Public/land/land.html');   
    }
    public function index()
    {
        $uid = $_REQUEST['uid'];
        echo $uid;
    }
    /**
    +----------------------------------------------------------
    * 探针模式
    +----------------------------------------------------------
    */
    public function checkEnv()
    {
        $pid=Session::get('p_id');
    	if(empty($pid)){
          header("Location:land");
        }
        load('pointer',THINK_PATH.'/Tpl/Autoindex');//载入探针函数
        $env_table = check_env();//根据当前函数获取当前环境
    }
     public function doLogin() {
         $back=array('back_data'=>null,
                    'back_info'=>'',
                    'back_status'=> 1,
                    'back_type'=>'json'
         ); 
        $username = $_POST["username"];    
        $password = md5($_POST["password"]);
      
        if(empty($_POST['username'])) {
             $back['back_info'] ='用户名为空';
              $back['back_status'] = 1;
             $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        }elseif (empty($_POST['password'])){
             $back['back_info'] ='密码为空';
             $back['back_status'] = 1;
             $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        }     
        //生成认证条件
        $map = array();
        $map["email"] = $username;       
        $userDao = D('Parent');
        $user = $userDao->where($map)->find();          
        //使用用户名、密码和状态的方式进行认证
        if(false === $user) {
             $back['back_info'] = '用户名不存在或已禁用';
             $back['back_status'] = 1;
             $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        }else {
            if($user['email']!==$username) {    
             $back['back_info']= '帐号错误！';
             $back['back_status'] = 1;
             $this->ajaxReturn( $back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
            //$this->error('帐号错误！');
            }
            if($user['password'] !==$password) {
             $back['back_info'] =  '密码错误！';
             $back['back_status'] = 1;
             $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
            //$this->error('密码错误！');
            }
        }
        $condition['pid']=$user['p_id'];
        $childList = M('User')->where($condition)->findAll();       
        $userIdList=array();
        if($childList){
        foreach($childList AS $key=>$val){
         $userIdList[$key]['uid']   =$val['u_id'];
         $userIdList[$key]['name']   =$val['name'];       
        }
        Session::set('userIdList',$userIdList);
        Session::set('uid',$userIdList[0]['uid']);
        }
        $_SESSION[C('USER_AUTH_KEY')] = $user['p_id'];
        $userDao->setField('lastLoginTime',time(),"p_id=".$user['p_id']);
 //     记录登陆状态        
        Session::set('username',$username);
        Session::set('p_id',$user['p_id']);
        Session::set('nick',$user['nick']);
        Session::set('uname',$userIdList[0]['name']);
        Session::set('userInfo',$user);
        $back['back_status'] = 2;
        Cookie::set('username',$username,36000000);
        $this->ajaxReturn($userIdList,$back['back_info'],2,$back['back_type']);
	}
    /**
     * @author sudi
     * @data 2012年1月6日18:33:02
     *、
     */
     public function main()
     {
        $pid=Session::get('p_id');
    	if(empty($pid)){
         header("Location:land");
        }
        $this->display('Tpl/default/Public/main/main.html');
     }
    /**
     * @author sudi
     * @data 2012年1月6日
     * 验证用户名
     */
     public function check_email()
     {  
         $back=array('back_data'=>null,
                    'back_info'=>'',
                    'back_status'=> 0,
                    'back_type'=>'json'
         );
        $username = $_POST["username"]; 
        if(empty($username))
        {
          $back['back_status'] = 1;
          $back['back_info'] = '用户名不能为空';
          $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        }
     }
     /**
     * @author sudi
     * @data 2012年1月6日
     * 验证密码
     */
     public function check_pwd()
     {          
         $back=array('back_data'=>null,
                    'back_info'=>'',
                    'back_status'=> 0,
                    'back_type'=>'json'
         );
        $password = $_POST["password"]; 
        if(empty($password))
        {
          $back['back_status'] = 1;
          $back['back_info'] = '密码不能为空';
          $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        }
     } 
   /**
     * @author sudi
     * @data 2012年3月21日
     * 查找孩子
     */   
     
     public function selectChild()
     {
        $username = $_REQUEST['selectname'];
        $Udao = M('User');
        $condition['name'] =$username;
        $List = $Udao->where($condition)->findAll();
        foreach($List AS $key=>$val){
          $List[$key]['reg_date']=date('Y-m-d h:m',$val['reg_date']); 
        }
        $this->assign('list',$List);
        $this->display('Tpl/default/Public/maincontent1/selectchild.html');
        
     }
     /**
      * 更改图像
      * @author sudi
      */
      public function headPhoto()
      {
         $photo=$_FILES['photo'];
      //获得各个图片信息
           $name=$photo['name'];
           $tmp_name=$photo["tmp_name"];
           $type=$photo["type"];
           $size=$photo["size"];
           $err = $photo["error"];
           $path = "/home/Tpl/default/Public/upload/head/".$name;
           $uploadfile = SITE_PATH.$path;
           $maxsize=800*1024;          //最大允许上许文件大小
            if($name=="")                                             //文件名为空
             {
             echo"<script>alert('请先选择要上传的图片文件!'); 
             window.history.back();</script>";
             }
            if($type!="image/pjpeg" && $type!="image/jpeg" && $type!="image/gif")//文件类型不在指定范围
            {
             echo"<script>alert('上传文件只可以是JPEG或GIF类型的!');
             window.history.back();</script>";
             exit;
            }
            if($size>$maxsize)                                       //超过规定大小
            {
             echo"<script>alert('上传文件大小不能超过800K! ');window.history.back();</script>";
             exit;
            }
     
        if($err>0){
            switch($err) 
            { 
            case 1: echo "<script>alert('文件大小超过服务器限制! ');window.history.back();</script>"; 
            break; 
            case 2: echo "<script>alert('上传文件太大小! ');window.history.back();</script>"; 
            break; 
            case 3: echo "<script>alert('文件至加载一半，请重新加载! ');window.history.back();</script>"; 
            break; 
            case 4: echo "<script>alert('文件加载失败! ');window.history.back();</script>"; 
            break; 
            } 
          }          
         $uid = Session::get('uid');        
         if($uid==0)                                             //文件名为空
         {
         echo"<script>alert('请确认是否登录，或者长时间离开浏览器!'); 
         window.history.back();</script>";
         }
         $condition['u_id'] = Session::get('uid'); 
         $data['picture'] = $name;
         $lastid = M('User')->where($condition)->save($data);
         if($lastid>0){
          if(move_uploaded_file($tmp_name,$uploadfile))
            {
            $this->showChildTo($uid);
            }
          else if (copy($tmp_name,$uploadfile))
            {
            $this->showChildTo($uid);
            }
          else
            return false; 
        }     
        else
            return false;  
      }
       
     /**
     *请求注册页面 
     * @author agui
     * @date 2012-1-6 1:34:03
     */
     public function selectitem()
     {
        $item = $_POST('item');  
     }    
  
        /**
     *登陆shoye 
     * @author agui
     * @date 2012-1-6 1:34:03
     */
      public function tohome()
      {  
        $pid=Session::get('p_id');
        $parentcond['p_id'] = $pid;
        $parent = M('Parent')->where($parentcond)->find();     
        $userid = Session::get('uid');
        $condition['u_id'] = $userid;
        $user = M('User')->where($condition)->find();      
        $Vdao = M('Visits');
        $condlist['visitedid'] = $userid;
         $VisitList = $Vdao->where($condlist)->findAll();
         if(sizeof($VisitList)>6)
         {
         $start = sizeof($VisitList);
         $VisitList =$Vdao->where($condition)->order('vtime desc')->limit($start,6)->select();
         }
    //   获得user的信息
         $vistors=null;
         foreach($VisitList AS $key=>$val){
            $usid = $val['visitid'];      
            $vistors[$key]=D('user')->where('u_id='.$usid)->find(); 
         }
         //最新的心情
        $scondition['uid'] = $userid;
        $ShareList = M('Share')->where($scondition)->order('id desc')->find();
        if($ShareList['id']>0){
           $ShareList['ctime'] = date('Y-m-d H:i',$ShareList['ctime']);
        }else{
           $ShareList['content'] ="快点击[分享]自己的每天的心情！"; 
           $ShareList['ctime'] = date('Y-m-d H:i:s',time()); 
        }
        $userIdList=Session::get('userIdList');
        Session::set('childName',$userIdList['name']);         
        $this->assign('userIdList',$userIdList); 
        $this->assign('shareList',$ShareList);
        $this->assign('visit',$vistors); 
        $this->assign('user',$user);
        $this->assign('parent',$parent);
        $this->assign('username',$user['name']);
        $this->display('Tpl/default/Public/maincontent1/maincontent.html');      
      }    
     /**
     *登陆跳转 
     * @author agui
     * @date 2012-1-6 1:34:03
     */
      public function tomain()
      { 
         $pid=Session::get('p_id');
         if(empty($pid)){
             header("Location:land");
         }
         $userIdList=Session::get('userIdList');
         Session::set('childName',$userIdList['name']);         
         $this->assign('userIdList',$userIdList);           
         $this->display('Tpl/default/Public/main/main.html');   
          
       }  
  
    /**
     *登陆跳转 
     * @author agui
     * @date 2012-1-6 1:34:03
     */
      public function toparent()
      {   
         $pid=Session::get('p_id');
         if(empty($pid)){
          header("Location:land");
         }
         $condition['p_id'] = $pid;
         $Udao = M('Parent');
         $parentinfo = $Udao->where($condition)->find();
         $name = $parentinfo['nick'];
         $scondition['pid'] = $pid;
         $ShareList = M('Pshare')->field('id,pid,ctime,content')->where($scondition)->order('id desc')->find();
           if($ShareList['id']>0){
               $ShareList['ctime'] = date('Y-m-d H:i',$ShareList['ctime']);
            }else{       
               $ShareList['content'] ="快点击[分享]自己的每天的心情！"; 
               $ShareList['ctime'] = date('Y-m-d H:i',time()); 
            }
         $Share = M('Pshare')->where($scondition)->order('id desc')->findAll();
         foreach($Share AS $key=>$val){
            $Share[$key]['ctime'] =  date('Y-m-d H:i',$val['ctime']);
         }
         $InfoList = M('Parentinfo')->where($scondition)->find();
         $this->assign('infoList',$InfoList);
         $this->assign('shareList',$ShareList);
         $this->assign('share',$Share);
         $this->assign('parent',$parentinfo);
         $this->assign('parentname',$name);
         $this->assign('parentid',$pid);    
         $this->display('Tpl/default/Public/main/parent.html');      
      } 
       /**
      * 更改图像
      * @author sudi
      */  
      function parentPhoto()
      {
        $pid = Session::get('p_id');
         if($pid==0)                                             //文件名为空
         {
         echo"<script>alert('请确认是否登录，或者长时间离开浏览器!'); 
         window.history.back();</script>";
         }  
        $photo=$_FILES['photo'];
      //获得各个图片信息
           $name=$photo['name'].'_'.$pid;          
           $tmp_name=$photo["tmp_name"];
           $type=$photo["type"];
           $size=$photo["size"];
           $err = $photo["error"];
           $path = "/home/Tpl/default/Public/upload/head/".$name;
           $uploadfile = SITE_PATH.$path;
           $maxsize=800*1024;          //最大允许上许文件大小
            if($name=="")                                             //文件名为空
             {
             echo"<script>alert('请先选择要上传的图片文件!'); 
             window.history.back();</script>";
             }
            if($type!="image/pjpeg" && $type!="image/jpeg" && $type!="image/gif")//文件类型不在指定范围
            {
             echo"<script>alert('上传文件只可以是JPEG或GIF类型的!');
             window.history.back();</script>";
             exit;
            }
            if($size>$maxsize)                                       //超过规定大小
            {
             echo"<script>alert('上传文件大小不能超过800K! ');window.history.back();</script>";
             exit;
            }    
          if($err>0){
            switch($err) 
            { 
            case 1: echo "<script>alert('文件大小超过服务器限制! ');window.history.back();</script>"; 
            break; 
            case 2: echo "<script>alert('上传文件太大小! ');window.history.back();</script>"; 
            break; 
            case 3: echo "<script>alert('文件至加载一半，请重新加载! ');window.history.back();</script>"; 
            break; 
            case 4: echo "<script>alert('文件加载失败! ');window.history.back();</script>"; 
            break; 
            } 
          }          
         $parentcond['p_id'] = $pid; 
         $data['picture'] = $name;
         $list = M('Parent')->where($parentcond)->find();
         $parentid = M('Parent')->where($parentcond)->save($data);
         //dump($parentid);
         $pid = $list['p_id'];
         if($pid>0){
          if(move_uploaded_file($tmp_name,$uploadfile))
            {
            $this->toparent();
            }
          else if (copy($tmp_name,$uploadfile))
            {
            $this->toparent();
            }
          else
            return false; 
        }     
        else
            return false;  
      }
    /**
     *请求注册页面 
     * @author agui
     * @date 2012-1-6 1:34:03
     */
      public function register()
      {      
        $list = M('User')->order('u_id desc')->findAll();
        $user1 = $list[0];
        $user2 = $list[1];
        $this->assign('user1',$user1);
        $this->assign('user2',$user2);
        $this->display('Tpl/default/Public/register/register.html');      
      }
        /**
         * 
        *登陆跳转 添加孩子界面
        * @author sudi
        * @date 2012-3-30 2:34:03
        */
       public function toAddChild(){
             $list = M('User')->order('u_id desc')->findAll();
            $user1 = $list[0];
            $user2 = $list[1];
            $this->assign('user1',$user1);
            $this->assign('user2',$user2);
            $this->display('Tpl/default/Public/register/addchild.html');  
       }
   
       /**
        * 
        *登陆跳转 tothird
        * @author agui
        * @date 2012-1-6 1:34:03
        */
        public function doAddChild()
        {    
           $pid=Session::get('p_id');
           if(empty($pid)){
              echo "<script>alert('注册没有成功，请重新注册 ');window.history.back();</script>";
           }
           $back=array('back_data'=>null,
                    'back_info'=>'',
                    'back_status'=> 0,
                    'back_type'=>'json'
           );
           $data['name']=$_REQUEST['name'];
           $data['netweb']=$_REQUEST['netweb'];
           $data['pwd']=md5($_REQUEST['password']);
           $data['birthday']=$_REQUEST['birthday'];
           $data['sex']=$_REQUEST['sex'];
           if($data['sex']==1){
            $data['picture']="defaultboy.png";
           }else{
             $data['picture']="defaultgirl.png";
           }
           $net = $_REQUEST['email'].'tang.com';
           $data['pid'] = $pid;
           $data['reg_date']=time();
           $Dao=M('user');  
           $result=$Dao->add($data);
          if($result>0){                    
            $back['back_status']=1;
            $back['back_info']='孩子信息已成功添加！';
            //搜索孩子
          //  $condition['pid']=$pid;
//            $childList = M('User')->where($condition)->findAll();       
//            $userIdList=array();
//            if($childList){
//            foreach($childList AS $key=>$val){
//                 $userIdList[$key]['uid']   =$val['u_id'];
//                 $userIdList[$key]['name']   =$val['name'];       
//                }
//            Session::set('userIdList',$userIdList);
//            $uid =  Session::get('uid');  
//            //把孩子信息存入session
//            Session::set('uid',$uid);
//            Session::set('uname',$data['name']);
           $this->ajaxReturn(null,$back['back_info'],1,$back['back_type']);  
          }
          else
          {        
           $back['back_info']='孩子信息添加失败了！';
           $this->ajaxReturn(null,$back['back_info'],0,$back['back_type']);
          }   
        }       
    /**
     *处理注册 
     */
      public function doRegister()
        
    	{               
	    $back=array('back_data'=>null,
                    'back_info'=>'',
                    'back_status'=> 0,
                    'back_type'=>'json'
         );  	
	  // 参数合法性检查
		$required_field = array(
			'email'		=> 'Email',
			'name'  => '用户名',
			'password'	=> '密码'
		//	'repassword'=> '密码'
		);           
		foreach ($required_field as $k => $v)
        {
			if (empty($_POST[$k]))
            {
		   $back['back_info']=$v.'不可为空';
           $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
           }
           }
       //     if (!$this->isValidNickName($_POST['name']))
        //  {
	     //   $back['back_info']='用户名不符合要求或已被使用';
            
        //    $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
         //   }	
    	if (!$this->isValidEmail($_POST['email']))
        {
            	
		   	$back['back_info']='邮箱填写格式有误';
            
            $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
		}      
	//	if (strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'])
//		//	$this->error('密码必须为6-16位，且两次必须相同');
//          {  $back['back_info']='密码必须为6-16位，且两次必须相同';
//             $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
//            }
//          //  $this->ajaxReturn('',"密码必须为6-16位，且两次必须相同",'0');
		if (!$this->isEmailAvailable($_POST['email']))
           {
			  $back['back_info']='Email已经被使用，请重新输入';
            
            $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
            }

    		$data['email']     = $_POST['email'];
    		$data['password']  = md5($_POST['password']);
            include('../ThinkPHP/Common/extend.php'); 
           	$data['nick']	   = t($_POST['name']);
            $data['sex']	   = t($_POST['sex']);
    		$data['ctime']	   = time();
            if($data['sex'] === '男'){
                $data['picture'] = "father.png";
            }else{
               $data['picture'] = "mother.png";
            }
           
	//	$data['is_active'] = $need_email_activate ? 0 : 1;
    		if (!($pid = D('Parent', 'home')->add($data)))
            {
		//	$this->error('抱歉: 注册失败，请稍后重试');
            $back['back_info']='抱歉: 注册失败，请稍后重试';
            
            $this->ajaxReturn($back['back_data'],$back['back_info'],0,$back['back_type']);
            }else{         
  	//	if ($need_email_activate == 1) { // 邮件激活
	//		$this->activate($p_id, $_POST['email'], $invite_code);
	//	} else {
			// 置为已登陆, 供完善个人资料时使用
		//	service('Passport')->loginLocal($p_id);
            if(!empty($data['passowrd'])){
                ($data['password']='');
            }
                // $p_id = D('Parent', 'home')->add($data);
            Session::set('userinfo',$data);
            Session::set('nick',$data['nick']);
    		Session::set('p_id',$pid);
    	    Session::set('register',1);  
            $back['back_status']=1;
            $back['back_info']='恭喜您，注册成功！';
            $this->ajaxReturn($back['back_data'],$back['back_info'],$back['back_status'],$back['back_type']);
        	}		
//		}
	}

   /**
     *访问公共页面
     *@author sudi 
     */
   public function getChild()
   {
     $uid=$_REQUEST['uid'];   
     $Child = A('Child');
     $Child->getChild($uid);     
   }
    /**
     *从公共获得图片详情
     *@author sudi 
     */
    function toList()
    {
       $uid = $_REQUEST['uid'];
       $albumid = $_REQUEST['aid'];
       $Upload = A('Upload');
       $Upload->getPublicChild($uid,$albumid);
    }
   /**
 * @time:2012年3月3日15:21:06
 * 显示单张图片
 */
    public function fullShow()
    {
        $picID = $_REQUEST['picid'];
        $Upload = A('Upload');
        $Upload->oneShow($picID);  
    }
     /**
 * @time:2012年3月3日15:21:06
 * 显示日志
 */
    public function noteinfo()
    {
        $nid = $_REQUEST['n_id'];
        $Note = A('Note');
        $Note->noteinfo($nid);  
    }   
 /**
 * 获取孩子信息
 * agui
 *
 */
   public function showChildInfo(){ 
    
    
     $uid=$_REQUEST['uid'];
     $con['u_id']=$uid;
      $user=D('user')->where($con)->find();
      
      Session::set('uname',$user['name']);
      Session::set('uid',$uid);
     $this->showChildTo($uid);
   }
   public function showChildTo($uid){     
     //根据uid得到孩子日志的信息
     $condition['u_id'] = $uid;
     $Udao = M('User');
     $userinfo = $Udao->where($condition)->find();
     $name = $userinfo['name'];
     $scondition['uid'] = $uid;
     $ShareList = M('Share')->field('id,uid,ctime,content')->where($scondition)->order('id desc')->find();
       if($ShareList['id']>0){
           $ShareList['ctime'] = date('Y-m-d H:i',$ShareList['ctime']);
        }else{       
           $ShareList['content'] ="快点击[分享]自己的每天的心情！"; 
           $ShareList['ctime'] = date('Y-m-d H:i',time()); 
        }
   //获得最喜爱的东西的
     $photocond['uid'] = $uid; 
	 $Plist=M('Photos')->where($photocond)->order('id desc')->find();
     if($Plist['id']>0)
     {
       $Plist['ctime']=date('Y-m-d H:i',$Plist['ctime']);
     }
     else
     {
        $Plist['ctime']=date('Y-m-d H:i',time());
        $Plist['ph_name']="default.png";
      
     }
     $notecond['uid'] = $uid; 
     $Nlist=M('Note')->where($notecond)->order('n_id desc')->find();
     if($Nlist['n_id']>0)
     {
       $Nlist['ctime']=date('Y-m-d H:i',$Plist['ctime']);
     }else
     {
        $Nlist['ctime']=date('Y-m-d H:i',time());
        $Nlist['title']="您还没有写过博文！";
     }  
     $this->assign('plist',$Plist);
     $this->assign('nlist',$Nlist);
     $this->assign('shareList',$ShareList);
     $this->assign('user',$userinfo);
     $this->assign('username',$name);
     $this->assign('userid',$uid); 
    
     $this->display('Tpl/default/Public/main/child.html');
 }
 

 public function showChildnew(){
     $uid=$_REQUEST['uid'];
 //根据uid得到孩子日志的信息
 
     $condition['uid']=$uid;

     $summaryList=D('summary')->where($condition)->order('ctime desc')->findAll();
     foreach($summaryList AS $key=>$val){
    if($val['type']==1){
        $where['id']=$val['tid'];
      $first=D('first')->where($where)->find();
    //  $allList[$key]  = $first;
     $firstList[$key]=$first['content'];
        
    }
      if($val['type']==2){
        $where['id']=$val['tid'];
      $favorite=D('favorite')->where($where)->find();
  //    $allList[$key]  = $favorite;
      $favoriteList[$key]=$favorite['content'];   
    }
    if($val['type']==3){
        $where['n_id']=$val['tid'];
      $note=D('note')->where($where)->find();
  //    $allList[$key] = $note;
        
    }
      if($val['type']==4){
        $where['v_id']=$val['tid'];
      $video=D('video')->where($where)->find();
  //    $allList[$key]= $video;
       $allList['video_title'][$key]=$video['title'];    
    }
     }
    
     $this->assign("allList",$allList);
    
     $this->display('Tpl/default/Public/main/child.html');
 }
 
    /**
     * @author sudi 
     * @date 2012.1.5
     * 用户验证
     */
     public function checkName(){
        $email = $_POST['username'];
        $user =  M('Parent')->find($email);
		if(!rmpty($user)){
			$this->success('用户名正确~');
		}else{
			$this->error('用户名错误！');
		}
	}
	public function checkLogin(){
	    $email = $_POST['username'];
        $user =  M('Parent')->find($email);
		if(!rmpty($user)){
			$this->ajaxReturn($_POST['username'],'用户名正确~',1);
			// success 方法返回
			//$this->success('用户名正确~',true);
			// 加载了 Js/Form/CheckForm.js 类库或提交了 ajax=1 隐藏表单元素
			//$this->success('用户名正确~');
		}else{
			$this->ajaxReturn('','用户名错误！',0);
			// error 方法返回
			//$this->error('用户名错误！',true);
			// 加载了 Js/Form/CheckForm.js 类库或提交了 ajax=1 隐藏表单元素
			//$this->error('用户名错误！');
		}
	}
    public function to_file()
    {
        $this->display('Tpl/default/Public/uplaodfile.html');
    }
    
    
    
    /**
     * 
     * 
     
    public void ProcessRequest(HttpContext context)
    {
    context.Response.ContentType = "text/plain";   
    context.Response.Charset = "utf-8";   

   HttpPostedFile file = context.Request.Files["Filedata"];   
    string  uploadPath = 
        HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";  

    if (file != null)  
    {  
       if (!Directory.Exists(uploadPath))  
       {  
           Directory.CreateDirectory(uploadPath);  
       }   
       file.SaveAs(uploadPath + file.FileName);  
        //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
       context.Response.Write("1");  
    }   
    else  
    {   
        context.Response.Write("0");   
    }  
}*/

	public function resendEmail() {
	   
       $val=new ValidationService();
		$invite = $val->getValidation();
		$this->activate(intval($_GET['uid']), $_GET['email'], $invite, 1);
	}

	//发送激活邮件
	public function activate() {
		//设置激活路径
        $userinfo=Session::get('userinfo');
        if(empty($userinfo)){
           $this->redirect(U('Index/index')); 
        }
         $data=$userinfo;
         $uid=$data['uid'];
         $email=$data['email'];
         $invite='';
         $is_resend = 0;
         $val=new ValidationService();
		$activate_url  = $val->addValidation($uid, '', U('Public/doActivate'), 'register_activate', serialize($invite));
		if ($invite) {
			$this->assign('invite', $invite);
		}
		$this->assign('url',$activate_url);

		//设置邮件模板
		$body ="
感谢您的注册!<br>".

"请马上点击以下注册确认链接，激活您的帐号！<br>".

"<a href='".$activate_url."' target='_blank'>测试</a><br/>".

"如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>".

"如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。";
		// 发送邮件
		global $ts;
         $mailserver=new MailService();
		$email_sent = $mailserver->send_email($email, "激活棒棒糖帐号",$body);
		
		// 渲染输出
		if ($email_sent) {
			$email_info = explode("@", $email);
			switch ($email_info[1]) {
				case "qq.com"    : $email_url = "mail.qq.com";break;
				case "163.com"   : $email_url = "mail.163.com";break;
				case "126.com"   : $email_url = "mail.126.com";break;
				case "gmail.com" : $email_url = "mail.google.com";break;
				default          : $email_url = "mail.".$email_info[1];
			}
			
			$this->assign("uid",$uid);
			$this->assign('email', $email);
			$this->assign('is_resend', $is_resend);
			$this->assign("email_url",$email_url);
			$this->display('activate');
		}else {
			$this->assign('jumpUrl', U('Public/userinfo'));
			$this->error('抱歉: 邮件发送失败，请稍后重试');
		}
	}
	
	public function doActivate() {
		$invite = service('Validation')->getValidation();
		if (!$invite) {
			$this->assign('jumpUrl', U('home/Public/register'));
        	$this->error('抱歉: 激活码错误，请重新注册');
		}
		$uid = $invite['from_uid'];
        
        $user = M('user')->where("`uid`=$uid")->find();
        if ($user['is_active'] == 1) {
        	$this->assign('jumpUrl', U('home/Public/login'));
        	$this->success('您的帐号已激活');
        	exit;
        } else if ($user['is_active'] == 0) {
        	//激活帐户
        	$res = M('user')->where("`uid`=$uid")->setField('is_active', 1);
        	if (!$res) $this->error('抱歉: 激活失败');
        	
			service('Passport')->registerLogin($user);
			
			//关联操作
			$this->registerRelation($user['uid'], $invite);
			
			service('Validation')->unsetValidation();

			$this->assign('jumpUrl', U('home/Account/index'));
			$this->success("恭喜: 激活成功");
        } else {
        	$this->assign('jumpUrl', U('home/Public/register'));
        	$this->error('抱歉: 激活码错误，请重新注册');
        }
	}
	
	public function sendPassword() {
		$this->display();
	}
	
	public function doSendPassword() {
		$_POST["email"]	= t($_POST["email"]);
		if ( !$this->isValidEmail($_POST['email']) )
			$this->error('邮箱格式错误');
		
		$user =	M("user")->where('`email`="' . $_POST['email'] . '"')->find();
		
        if(!$user) {
        	$this->error("该邮箱没有注册");
        }else {
            $code = base64_encode( $user["uid"] . "." . md5($user["uid"] . '+' . $user["password"]) );
            $url  = U('home/Public/resetPassword', array('code'=>$code));
            $body = <<<EOD
<strong>{$user["uname"]}，你好: </strong><br/>

您只需通过点击下面的链接重置您的密码: <br/>

<a href="$url">$url</a><br/>

如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>

如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。
EOD;
			
			global $ts;
			$email_sent = service('Mail')->send_email($user['email'], "重置{$ts['site']['site_name']}密码", $body);
			
            if ($email_sent) {
	            $this->assign('jumpUrl', SITE_URL);
	            $this->success("已把密码发送到你的邮箱$email中，请注意查收");
            }else {
            	$this->error('抱歉: 邮件发送失败，请稍好重试');
            }
		}
	}
	
	public function resetPassword() {
		$code = explode('.', base64_decode($_GET['code']));
        $user = M('user')->where('`uid`=' . $code[0])->find();
        
        if ( $code[1] == md5($code[0].'+'.$user["password"]) ) {
	        $this->assign('email',$user["email"]);
	        $this->assign('code', $_GET['code']);
	        $this->display();
        }else {
        	$this->error("抱歉: 链接错误");
        }
	}
	
	public function doResetPassword() {
		if($_POST["password"] != $_POST["repassword"]) {
        	$this->error("输入的两次密码必须一致，请重新输入");
        }
        
		$code = explode('.', base64_decode($_POST['code']));
        $user = M('user')->where('`uid`=' . $code[0])->find();
        
        if ( $code[1] == md5($code[0] . '+' . $user["password"]) ) {
	        $user['password'] = md5($_POST['password']);
	        $res = M('user')->save($user);
	        if ($res) {
	        	$this->assign('jumpUrl', U('home/Public/login'));
	        	$this->success('保存成功');
	        }else {
	        	$this->error('抱歉: 保存失败，请稍后重试');
	        }
        }else {
        	$this->error("抱歉: 安全码错误");
        }
	}
	
	public function doModifyEmail() {
    	if ( !$validation = service('Validation')->getValidation() ) {
    		$this->error('验证码错误');
    	}
    	if ( "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"] != $validation['target_url'] ) {
    		$this->error('URL错误');
		}
    	
    	$validation['data'] = unserialize($validation['data']);
    	$map['uid']			= $validation['from_uid'];
    	$map['email']		= $validation['data']['oldemail'];
		if ( M('user')->where($map)->setField('email', $validation['data']['email']) ) {
			service('Validation')->unsetValidation();
			service('Passport')->logoutLocal();
			$this->assign('jumpUrl', SITE_URL);
			$this->success('激活新Email成功，请重新登录');
		}else {
			$this->error('抱歉: 激活新Email失败');
		}
    }
	
	//检查Email地址是否合法
	public function isValidEmail($email) {
		
			return preg_match("/[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$/i", $email) !== 0;
		
	}

	//检查Email是否可用
	public function isEmailAvailable($email = null) {
		$return_type = empty($email) ? 'ajax' 		   : 'return';
		$email		 = empty($email) ? $_POST['email'] : $email;

		$res = M('parent')->where('`email`="'.$email.'"')->find();
	

		if ( !$res ) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo '邮箱已被占用';
			else return false;
		}
	}
	
	//检查昵称是否符合规则，且是否为唯一
	
	public function isValidNickName($name)
	{
	    $return_type  = empty($name)  ? 'ajax' 		   			: 'return';
		$name		  = empty($name)  ? $this->t($_POST['name']) 	: $name;
       
        //    if (!$this->isLegalUsername($name)) {
//		      if ($return_type === 'ajax') { echo '2-16位的中英文、数字、下划线、中划线';return; }
//			else return false;
//		}

		if ($this->mid) {
			$res = M('parent')->where("nick='{$name}' AND p_id<>{$this->mid}")->count();
           	$nick = M('parent')->getField('nick',"p_id={$this->mid}");
		
		} else {
			$res = M('parent')->where("nick='{$name}'")->count();
			
		}

		if ( !$res ) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo '此用户名已被使用';
			else return false;
		}
	}
	
	//检查是否真实姓名。支持ajax和return
	public function isValidRealName($name = null, $opt_register = null) {
		$return_type  = empty($name) 		 ? 'ajax' 							: 'return';
		$name		  = empty($name) 		 ? t($_POST['name']) 				: $name;
         $xs=new XdataService();
		$opt_register = empty($opt_register) ?$xs->lget('register') : $opt_register;
		
		if ($opt_register['register_realname_check'] == 1) {
			$lastname = explode(',', $opt_register['register_lastname']);
			$res = in_array( substr($name, 0, 3), $lastname ) || in_array( substr($name, 0, 6), $lastname );
		}else {
			$res = true;
		}
		
		if ($res) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo 'fail';
			else return false;
		}
	}
	
     
	
	public function verify() {
       
       import('@.ORG.Image');
  
       Image::buildImageVerify();
	}
	//检验验证码是否正确  
  public function verifyCheck() {  
     //防止页面乱码  
          header('Content-type:text/html;charset=utf-8');  
       
     if (md5($_POST['verify']) != Session::get('verify')) {  
      $this->ajaxReturn(null,'验证码错误',0,'json');
    }  
      
    }  

    //上传图片
    public function uploadpic(){
    	if( $_FILES['pic'] ){
    		//执行上传操作
    		$savePath =  $this->getSaveTempPath();
    		$filename = md5( time().'teste' ).'.'.substr($_FILES['pic']['name'],strpos($_FILES['pic']['name'],'.')+1);
	    	if(@copy($_FILES['pic']['tmp_name'], $savePath.'/'.$filename) || @move_uploaded_file($_FILES['pic']['tmp_name'], $savePath.'/'.$filename)) 
	        {
	        	$result['boolen']    = 1;
	        	$result['type_data'] = 'temp/'.$filename;
	        	$result['picurl']    = __UPLOAD__.'/temp/'.$filename;
	        } else {
	        	$result['boolen']    = 0;
	        	$result['message']   = '上传失败';
	        }
    	}else{
        	$result['boolen']    = 0;
        	$result['message']   = '上传失败';
    	}
    	
    	exit( json_encode( $result ) );
    }
    
    //上传临时文件
	public function getSaveTempPath(){
        $savePath = SITE_PATH.'/data/uploads/temp';
        if( !file_exists( $savePath ) ) mk_dir( $savePath  );
        return $savePath;
    }
    
   
	
	public function error404() {
		$this->display('404');
	}
        /**
 * 检查给定的用户名是否合法
 * 
 * 合法的用户名由2-10位的中英文/数字/下划线/减号组成
 * @author agui
 * @date 2012 01 02 20:34
 * @param string $username
 * @return boolean
 */
function isLegalUsername( $username )
{
   // GB2312: preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_-]+$/", $username)
   return preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_-]+$/u", $username) && 
   		  mb_strlen($username, 'UTF-8') >= 2 && 
   		  mb_strlen($username, 'UTF-8') <= 16;
}

/**
 * 转换为安全的纯文本
 * 
 * @param string  $text
 * @param boolean $parse_br    是否转换换行符
 * @param int     $quote_style ENT_NOQUOTES:(默认)不过滤单引号和双引号 ENT_QUOTES:过滤单引号和双引号 ENT_COMPAT:过滤双引号,而不过滤单引号
 * @return string|null string:被转换的字符串 null:参数错误
 */
function t($text, $parse_br = false, $quote_style = ENT_NOQUOTES)
{
	if (is_numeric($text))
		$text = (string)$text;
	
	if (!is_string($text))
		return null;
	
	if (!$parse_br) {
		$text = str_replace(array("\r","\n","\t"), ' ', $text);
	} else {
		$text = nl2br($text);
	}
	
	$text = stripslashes($text);
	$text = htmlspecialchars($text, $quote_style, 'UTF-8');
	
	return $text;
}
/**
 *创一个孩子 
 */
public function toAddAnother()
{
  
  $pid=Session::get('p_id');
  $parentcond['p_id'] = $pid;
  $parent = M('Parent')->where($parentcond)->find(); 
  $this->assign('parent',$parent); 
  $this->display('Tpl/default/Public/child/addchild.html');  
}
/**
 * 退出登陆
 * @author agui
 **/
 public function loginout(){
   Session::destroy();
   Session::clear();
   header("Location:land");
 } 
 public function checkMail(){
   $email=$_REQUEST['email'];
   
 if (!$this->isValidEmail($email))
        {
            	
		   	$back['back_info']='邮箱填写格式有误';
            
            $this->ajaxReturn(null,$back['back_info'],0,'json');
		} 
         $this->ajaxReturn(null,'',1,'json');  
}
}
?>